#include <string>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include <arpa/inet.h>

int main(int argc, char *argv[])
{
        if (argc < 3) {
                std::cerr << "usage " << argv[0] << " host port" << std::endl;
                return 1;
        }

        // Creates new socket
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd < 0) {
                std::cerr << "Error opening socket" << std::endl;
                return 1;
        }
        hostent* server = gethostbyname(argv[1]);
        if (server == NULL) {
                std::cerr << "No such host" << std::endl;
                return 1;
        }

        sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        //strcpy((char*)&serv_addr.sin_addr.s_addr, server->h_addr);
	inet_pton(AF_INET,argv[1],&serv_addr.sin_addr.s_addr);
        int portno = atoi(argv[2]);
        serv_addr.sin_port = htons(portno);
	
        if(connect(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
                std::cerr << "ERROR connecting" << std::endl;
                return 1;
        }
//	std::cout << "Please enter the message: ";
	std::cout << "Please enter the number: ";
	char buffer[256];
	int16_t value;
	for(int i = 0; i < 100; i++){
	memset(&value, 0, sizeof(value));
	value = i;
//	std::cout<< i << "  " << value <<std::endl;
//	std::cin >> value;
	value = htons(value);
	std::cout <<"After htons: "<< value <<std::endl;
	memset(buffer, 0, sizeof(buffer));
//	std::cin.getline(buffer,256);
//	int n = write(sockfd, buffer, strlen(buffer));
	int n = write(sockfd, &value, sizeof(value));
        if(n < 0) {
                std::cerr << "ERROR writing to socket" << std::endl;
                return 1;
        }
	usleep(500000);
	}//for
//	memset(buffer, 0, sizeof(buffer));
//	memset(&value, 0 , sizeof(value));
/*	n = read(sockfd, buffer, 255);
       	if(n < 0) {
                std::cerr << "ERROR reading from socket" << std::endl;
                return 1;
        }
        std::cout << buffer << std::endl;
*/	
        close(sockfd);


        return 0;
}
